package edu.lingnan.store.controller;

import cn.hutool.json.JSONUtil;
import edu.lingnan.store.common.ResultBean;
import edu.lingnan.store.entity.ShopCart;
import edu.lingnan.store.service.ShopCartService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (ShopCart)表控制层
 *
 * @author yinrui
 * @since 2021-04-10 14:04:29
 */
@RestController
@RequestMapping("shopCart")
public class ShopCartController {
    /**
     * 服务对象
     */
    @Resource
    private ShopCartService shopCartService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public ShopCart selectOne(Integer id) {
        return this.shopCartService.queryById(id);
    }

    @GetMapping("getCart")
    public ResultBean getCart(Integer userId){
        ResultBean resultBean = new ResultBean();
        List<ShopCart> list = shopCartService.getCart(userId);
        resultBean.setData(list);
        return resultBean;
    }

    @PostMapping("setCart")
    public ResultBean setCart(Integer userId,String carts){
        ResultBean resultBean = new ResultBean();
        //根据userId删除购物车
        int count = shopCartService.deleteCartByUserId(userId);
        if(count<0){
            resultBean.setSuccess(false);
            return resultBean;
        }
        //批量添加
        List<ShopCart> shopCarts = JSONUtil.toList(carts,ShopCart.class);
        System.out.println(userId);
        System.out.println(carts);
        System.out.println(shopCarts);
        resultBean.setSuccess(shopCartService.setCart(shopCarts)>0);
        return resultBean;
    }

}